package com.wang.util;


import com.wang.auto.addSet.AddSetAutoSend;
import com.wang.auto.addSet.AddSetControlUtil;
import com.wang.conf.AppData;
import com.wang.packpojo.ConMsg;
import com.wang.packpojo.ResultStatus;
import com.wang.pojo.*;
import com.wang.service.Custom2ControlService;
import com.wang.service.Custom2ControlServiceImpl;
import com.wang.service.Custom2ReturnService;
import com.wang.service.Custom2ReturnServiceImpl;
import com.wang.socket.OutBoundHandler;
import com.wang.socket.SocketMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wcy
 * @date 2024-07-30 16:43
 */
public class ControlUtil {

    //发送命令执行 暂时制作modbus 命令
    public static ResultStatus exeControlCommand(String devGId, Integer controlId) throws InterruptedException {

        ResultStatus msg = new ResultStatus();
        //判断该设备是否在线

        ConMsg conMsg = null;
        for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {
            System.out.println(entry.getValue().getDevice().getDevGId());
            if (entry.getValue().getDevice().getDevGId().equals(devGId)) {
                conMsg = entry.getValue();
                break;
            }
        }

        if (conMsg != null) {


            Custom2ControlService custom2ControlService = SpringUtil.getBean("custom2ControlServiceImpl", Custom2ControlServiceImpl.class);
            Custom2Control custom2Control =  custom2ControlService.getById(controlId);
            //对象锁
            Object object = new Object();

                //创建全局变量对象
                Map<String, Object> resultMap1 = new HashMap<>();
                //查询该指令返回的数据回复
                Custom2ReturnService custom2ReturnService = SpringUtil.getBean("custom2ReturnServiceImpl", Custom2ReturnServiceImpl.class);
                List<Custom2Return> custom2ReturnList = custom2ReturnService.selectListByControlId(controlId);


                resultMap1.put(controlId.toString(), null);

                if (AppData.returnMap.containsKey(devGId)) {
                    AppData.returnMap.get(devGId).put(controlId.toString(), null);
                } else {
                    AppData.returnMap.put(devGId, resultMap1);
                }
                ConMsg finalConMsg = conMsg;


                new Thread(() -> {
                    synchronized (object) {

                        //发送给设备

                        //去除所有的空格
                        byte[] commandByte = ModBusUtil.HexString2Bytes(custom2Control.getCommand());

                        OutBoundHandler.outData(finalConMsg.getCtx(), commandByte);
                        PrintUtil.print("服务端发送指令-->设备编码：" + devGId + "：" + custom2Control.getCommand());
                        //计数器  //小于10秒
                        int i = 0;
                        while (i < 600) {
                            Map<String, Object> resultMap = AppData.returnMap.get(devGId);

                            try {
                                Thread.sleep(50);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            if (resultMap != null && resultMap.size() > 0 && resultMap.containsKey(controlId.toString()) && resultMap.get(controlId.toString()) != null) {
                                System.out.println("开始激活");
                                object.notify();
                                break;
                            }
                            i++;
                        }
                        object.notify();
                    }

                }).start();
                synchronized (object) {
                    System.out.println("开始等待");
                    object.wait(30000L);
                }
                Map<String, Object> resultMap = AppData.returnMap.get(devGId);


                if (resultMap != null && resultMap.containsKey(custom2Control.getControlId().toString())) {


                    String result = (String) resultMap.get(custom2Control.getControlId().toString());

                    AppData.returnMap.get(devGId).remove(controlId.toString());
                    if (EmptyUtil.isNotNull(result)) {
                        PrintUtil.print("指令" + custom2Control.getCommand() + "http://返回结果:" + result);
                        //解析指令
                        //查询所有返回结果数据集合 比对值
                        //进行比对
                        if (custom2ReturnList.size() > 0) {
                            for (Custom2Return custom2Return : custom2ReturnList) {
                                String returnData = custom2Return.getControlReturnData().replaceAll(" ", "");
                                String resultData = result.replaceAll(" ", "");
                                if (returnData.equals(resultData)) {
                                    msg = new ResultStatus("success", custom2Control.getStatus());
                                }
                            }
                        } else {
                            msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息1");
                        }

                    } else {
                        msg = new ResultStatus("error", "设备无响应");
                    }

                } else {
                    msg = new ResultStatus("error", "设备响应超时，请稍后查看日志信息2");
                }
            } else {
            msg = new ResultStatus("error", "设备离线");
        }
        AppData.returnMap.get(devGId).remove(controlId.toString());
        return msg;
    }

}
